package com.example.literj.kt.internal.util

import com.example.literj.kt.core.Emitter
import java.util.concurrent.atomic.AtomicReference

class AtomicThrowable : AtomicReference<Throwable>() {
    fun terminate(): Throwable? {
        return ExceptionHelper.terminate(this)
    }

    fun tryAddThrowable(t: Throwable?): Boolean {
        return ExceptionHelper.addThrowable(this, t!!)
    }

    fun tryTerminateConsumer(consumer: Emitter<*>) {
        val ex = terminate()
        if (ex == null) {
            consumer.onComplete()
        } else if (ex != ExceptionHelper.TERMINATED) {
            consumer.onError(ex)
        }
    }
}